package algorithm;


import java.util.Arrays;

/**
 * 求数组数据的总和
 *
 * @author luoyalan
 * @date 2018/7/21
 */
public class Sum {

    public static int sum(int[] array) {
        if (array == null || array.length < 1) {
            return 0;
        }
        int result = 0;
        for (int i = 0; i < array.length; i++) {
            result += array[i];
        }
        return result;
    }

    public static double average(int[] arr) {
        if (arr == null || arr.length < 1) {
            return 0;
        }
        double result = 0;
        for (int i = 0; i < arr.length; i++) {
            result += arr[i];
        }
        return result / arr.length;
    }

    public static int max(int[] arr) {
        if (arr == null || arr.length < 1) {
            return 0;
        }
        int result = 0;
        for (int i = 0; i < arr.length; i++) {
            if (result < arr[i]) {
                result = arr[i];
            }
        }
        return result;
    }

    public static int min(int[] arr) {
        if (arr == null || arr.length < 1) {
            return 0;
        }
        int result = 0;
        for (int i = 0; i < arr.length; i++) {
            if (result > arr[i]) {
                result = arr[i];
            }
        }
        return result;
    }

    /**
     * 给分数排名
     *
     * @param arr
     * @return
     */
    public static int[] sort(int[] arr) {
        if (arr == null || arr.length < 1) {
            return null;
        }
        int[] rank = new int[arr.length];
        for (int i = 0; i < arr.length; i++) {
            int count = 1;
            for (int j = 0; j < arr.length; j++) {
                if (arr[i] < arr[j]) {
                    count++;
                }
            }
            rank[i] = count;
        }
        return rank;
    }

    public static int[][] sumTotal(int[][] score) {
        if (score == null || score.length < 1) {
            return null;
        }
        int length = score.length - 1;
        for (int i = 0; i < length; i++) {
            int sum = 0;
            for (int j = 0; j < score[i].length; j++) {
                sum += score[i][j];
            }
            score[length][score[i].length - 1] = sum;
        }
        return score;
    }

    public static int getGCD(int a, int b) {
        int c = a % b;
        if (c == 0) {
            return b;
        }
        return getGCD(b, c);
    }


    public static void main(String[] args) {
        int[] array = {1, 2, 3, 4, 6};
        System.out.println(sum(array));
        System.out.println(average(array));
        int[] score = {40, 13, 89, 52, 7};
        System.out.println(Arrays.toString(sort(score)));
        System.out.println(getGCD(16, 32));
    }
}
